<template>
  <!-- 参保记录与参保详情页面内容，通过type区分 -->
  <div id="InsuredIndex" class="editCard">
    <div class="staffInfo">
      <p>{{ editForm.realName }}</p>
      <span>部门：{{ editForm.departmentName }}</span>
      <span>岗位：{{ editForm.postName }}</span>
      <span>员工类型：{{ editForm.registerTypeDesc }}</span>
      <span>入职日期：{{ editForm.hireDate }}</span>
    </div>
    <el-card class="baseInfo">
      <div slot="header">
        基础信息
      </div>
      <el-form class="grid-col-2" label-width="130px">
        <el-form-item label="参保初始月份：">
          <span v-if="[1,4].includes(pageStatus)">{{ initDate == '0-00' ? '--' : initDate }}</span>
          <el-date-picker v-else value-format="yyyy-MM" @change="(date) => handleDateChange(date, 'init')" v-model="initDate" type="month" placeholder="请选择参保初始月份" />

        </el-form-item>
        <el-form-item v-if="pageStatus == 3" label="调整生效月份：">
          <el-date-picker v-model="effectDate" value-format="yyyy-MM" type="month" />
        </el-form-item>
        <el-form-item v-else-if="pageStatus == 4" label="补缴起始月份">
          <el-date-picker v-model="supplementaryPayDate" :picker-options="pickerOptions" class="monthrange" type="monthrange" value-format="yyyy-MM" />
        </el-form-item>
        <el-form-item v-else label="停保月份：">
          <!-- 当进行社保增员操作时，停保月份显示“--” -->
          <span>{{ pageStatus == 2 ? '--' : stopDate }}</span>
        </el-form-item>
        <el-form-item label="参保规则：">
          <el-select style="width:220px;" v-if="pageStatus > 1" placeholder="请选择参保规则" v-model="editForm.ssafId" clearable @change="handleRuleChange">
            <!-- ruleId -->
            <el-option v-for="item in ruleList" :key="item.ruleId" :label="item.ruleName" :value="item.ruleId">
            </el-option>
          </el-select>
          <span v-else>{{ editForm.ssafName }}</span>
        </el-form-item>
        <el-form-item label="参保城市：">
          <CitySelect v-if="pageStatus > 1" placeholder="参保城市" :disabled="!isEditable" :data.sync="editForm.ssafCityId" @change="handleCityChange" />
          <span v-else>{{ editForm.ssafCity }}</span>
        </el-form-item>
        <el-form-item v-if="pageStatus == 3" class="col-start-1 col-end-2" label="调整原因：">
          <el-input v-model="editForm.remarks" type="textarea" resize="none" :rows="2" :maxlength="50" show-word-limit />
        </el-form-item>
      </el-form>
    </el-card>
    <div>
      <el-card class="record" v-if="type == 1">

        <template slot="header">
          <p>参保记录</p>
        </template>
        <el-date-picker v-model="listQuery.queryYear" type="year" value-format="yyyy" placeholder="年份选择" class="searchDate" @change="searchRecordList" />
        <el-table border :data="editForm.isuredRecordList">
          <el-table-column prop="monthNumber" label="月份" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.monthNumber }}月</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" align="center">
            <template slot-scope="{}">
              <span>{{ editForm.realName }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="ssafName" label="参保方案"></el-table-column>
          <el-table-column align="center" prop="ssafCity" label="参保城市"></el-table-column>
          <el-table-column align="center" prop="personalSS" label="个人社保"></el-table-column>
          <el-table-column align="center" prop="companySS" label="公司社保"></el-table-column>
          <el-table-column align="center" prop="personalAF" label="个人公积金"></el-table-column>
          <el-table-column align="center" prop="companyAF" label="公司公积金"></el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="handleGoInsuredDetails(scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card class="details" v-else>
        <template slot="header">
          <p>参保记录</p>
        </template>
        <el-card>
          <template slot="header">
            <p class="detailsTitle">社保明细</p>
          </template>
          <EditableTable ref="editTable" :isEditable="isEditable" :tableData.sync="editForm.ssRuleItemList" :type="1" />
        </el-card>
        <el-card>
          <template slot="header">
            <p class="detailsTitle">公积金明细</p>
          </template>
          <EditableTable :tableData.sync="editForm.afRuleItemList" :isEditable="isEditable" :type="2" />
        </el-card>
        <div class="totalStatistics">
          <span>个人承担合计：<span class="redColorFont">{{ total.personalTotal }}</span></span>
          <span>公司承担合计：<span class="redColorFont">{{ total.companyTotal }}</span></span>
          <span>全部合计：<span class="redColorFont">{{ total.allTotal }}</span></span>
        </div>
      </el-card>
    </div>
    <div class="footer" v-if="pageStatus > 1">
      <el-button @click="handleGoBack">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </div>
    <template v-if="type == 1">
      <InsuredDetailsDialog :activeData="activeData" :pageStatus="1" :visible.sync="isShowDetail" />
    </template>
  </div>
</template>
<script>
import { math } from '@/util/math.js';
import EditableTable from './EditableTable.vue';
import CitySelect from './CitySelect.vue';
import InsuredDetailsDialog from './InsuredDetailsDialog.vue';
export default {
  name: 'InsuredIndex',
  components: {
    EditableTable,
    CitySelect,
    InsuredDetailsDialog
  },
  props: {
    type: {
      type: Number, // 1--参保记录 2--参保明细
      default: 1
    },
    pageStatus: {
      type: Number, // 1--查看 2--增员 3--编辑 4--补缴
      default: 1
    },
    infoData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    isAccount: { // 是否是在社保公积金台账页打开
      type: Boolean,
      default: false,
    }

  },
  data() {
    return {
      listQuery: { // 参保记录列表搜索条件
        queryYear: ''
      },
      editForm: {
        stopYear: 0, // 停保月份
        stopMonth: 0, // 停保月份
        initYear: 0, // 参保月份
        initMonth: 0, // 参保月份
        ssafCity: '', // 参保城市
        ssafCityId: 0, // 参保城市ID
        ssafId: null, // 参保规则id
        ssafName: '', // 参保规则名称
        isuredRecordModel: {
          ssafCity: '', // 参保城市
          ssafCityId: 0, // 参保城市ID
          ssafId: null, // 参保规则id
          ssafName: '', // 参保规则名称
        },
        ssRuleItemList: [],
        afRuleItemList: []
      },
      initialTableData: { // 社保及公积金表格初始值
        ssRuleItemList: [
          { projectName: '养老', baseNumber: '0.00', personalRatio: '0%', companyRatio: '0%', personalAmount: '0.00', companyAmount: '0.00', totalAmount: '0.00', ruleType: 1 },
          { projectName: '失业', baseNumber: '0.00', personalRatio: '0%', companyRatio: '0%', personalAmount: '0.00', companyAmount: '0.00', totalAmount: '0.00', ruleType: 1 },
          { projectName: '医疗', baseNumber: '0.00', personalRatio: '0%', companyRatio: '0%', personalAmount: '0.00', companyAmount: '0.00', totalAmount: '0.00', ruleType: 1 },
          { projectName: '工伤', baseNumber: '0.00', personalRatio: '0%', companyRatio: '0%', personalAmount: '0.00', companyAmount: '0.00', totalAmount: '0.00', ruleType: 1 },
        ],
        afRuleItemList: [
          { projectName: '公积金', baseNumber: '0.00', personalRatio: '0%', companyRatio: '0%', personalAmount: '0.00', companyAmount: '0.00', totalAmount: '0.00', ruleType: 2 },
        ],
      },
      ruleList: [], // 规则下拉框列表
      initDate: '', // 参保日期选择器显示数据
      effectDate: '', // 调整生效月份
      supplementaryPayDate: [], // 补缴起止时间
      stopDate: '', // 停保日期选择器显示数据
      isShowDetail: false, // 控制当前参保详情弹窗显示
      activeData: {}, // 当前要查看详情的参保明细数据
    };
  },
  computed: {
    // 补缴日期可选范围
    pickerOptions() {
      return {
        disabledDate: (time) => {
          // console.log('this.initDate', this.initDate, time);
          if (this.initDate) {
            return time.getTime() >= new Date(this.initDate).getTime();
          } else {
            return false;
          }
        }
      };
    },
    // 表格是否可编辑 -- 查看详情时不能修改，编辑时可以修改
    isEditable() {
      // 查看详情时不能编辑
      if (this.pageStatus == 1) return false;

      // 选定规则后不能编辑表格 
      if (this.editForm.ssafId && this.editForm.ssafId > 0) return false;
      return true;
    },
    total() {
      let personalTotal = 0.00, companyTotal = 0.00, allTotal = 0.00;

      console.log(this.editForm.ssRuleItemList, this.editForm.afRuleItemList);
      this.editForm.ssRuleItemList.map(e => {
        personalTotal = math.add(personalTotal, e.personalAmount == '' ? 0 : parseFloat(e.personalAmount));
        companyTotal = math.add(companyTotal, e.companyAmount == '' ? 0 : parseFloat(e.companyAmount));
      });
      this.editForm.afRuleItemList.map(e => {
        personalTotal = math.add(personalTotal, e.personalAmount == '' ? 0 : parseFloat(e.personalAmount));
        companyTotal = math.add(companyTotal, e.companyAmount == '' ? 0 : parseFloat(e.companyAmount));
      });
      personalTotal = personalTotal.toFixed(2);
      companyTotal = companyTotal.toFixed(2);
      allTotal = math.add(personalTotal, companyTotal).toFixed(2);
      console.log('重新计算总额', personalTotal, this.editForm);
      return {
        allTotal,
        personalTotal,
        companyTotal
      };
    },
  },
  methods: {

    /**
     * @description 暴露给父组件调用的 数据初始化方法
     */
    initPageData() {

      this.editForm = JSON.parse(JSON.stringify(this.infoData));
      if (this.type == 1) {
        this.searchRecordList();
        return;
      }
      // type == 2 进入的是参保明细页

      // 如果是增员编辑就获取规则下拉框列表数据
      this.pageStatus > 1 ? this.searchRuleSelectList() : '';

      if ([1, 3, 4].includes(this.pageStatus)) { // 查看 或 编辑 或 补缴
        // ssid为0改为null
        this.editForm.ssafId == 0 ? this.editForm.ssafId = null : '';
        if (this.editForm.isuredRecordModel) {
          this.editForm.isuredRecordModel.ssafId == 0 ? this.editForm.isuredRecordModel.ssafId = null : '';
        }
        // 对日期进行拼接

        const iYear = this.editForm.initYear == 0 ? '--' : this.editForm.initYear;
        let iMonth = this.editForm.initMonth == 0 ? '' : `0${this.editForm.initMonth}`.slice(-1);

        const sYear = this.editForm.stopYear == 0 ? '--' : this.editForm.stopYear;
        const sMonth = this.editForm.stopMonth == 0 ? '' : `0${this.editForm.stopMonth}`.slice(-1);
        this.initDate = `${iYear}-${iMonth}`;
        this.stopDate = `${sYear}-${sMonth}`;

        if(iMonth == '0') {
          iMonth = '1' + iMonth;
          this.initDate = `${iYear}-${iMonth}`;
          this.initMonth = `${iYear}-${iMonth}`;
        }
        this.initTableData();
      } else if (this.pageStatus == 2) { // 增员

        // 为社保和公积金表格赋初始值
        this.$set(this.editForm, 'ssRuleItemList', JSON.parse(JSON.stringify(this.initialTableData.ssRuleItemList)));
        this.$set(this.editForm, 'afRuleItemList', JSON.parse(JSON.stringify(this.initialTableData.afRuleItemList)));
        // this.editForm.ssRuleItemList = JSON.parse(JSON.stringify(this.initialTableData.ssRuleItemList));
        // this.editForm.afRuleItemList = JSON.parse(JSON.stringify(this.initialTableData.afRuleItemList));
      }
    },

    /**
     * @description 格式化表格中金额列数据（添加两位小数）
     */
    formatNumberCol(listData) {
      return listData.map(e => {
        for (const key in e) {
          if (['personalSS', 'companySS', 'personalAF', 'companyAF'].includes(key)) {
            e[key] = math.toFixed(e[key]);
          }
        }
        return e;
      });
    },

    /**
     * @description 格式化editForm中的社保公积金表格数据
     */
    initTableData() {
      // 调用editTable提供的方法，将数据转化为显示类型
      this.editForm = this.$refs.editTable.formatTableData(this.editForm, 2);
    },

    /**
     * @description 根据档案id获取参保记录列表
     */
    searchRecordList() {
      let params = {
        archiveId: this.infoData.id
      };
      this.listQuery.queryYear ? params.queryYear = this.listQuery.queryYear : '';
      this.$api.socialSecurity
        .ArchivesDetail(params)
        .then(res => {
          if (!res.data.data) {
            this.$message.warning(res.data.message);
            return;
          }
          res.data.data.isuredRecordList = this.formatNumberCol(res.data.data.isuredRecordList);
          if (this.editForm.isuredRecordList) {
            this.$set(this.editForm, 'isuredRecordList', res.data.data.isuredRecordList);
          } else {
            this.editForm = {
              ...res.data.data,
              ...this.editForm,
            };
          }

          this.initDate = this.editForm.initMonth ? this.editForm.initMonth : '--';
          this.stopDate = this.editForm.stopMonth ? this.editForm.stopMonth : '--';
        });
    },


    /**
     * @description 获取规则下拉框数据
     */
    searchRuleSelectList() {
      this.$api.socialSecurity
        .GetSsafRuleNameList()
        .then(res => {
          this.ruleList = res.data.data;
        });
    },
    searhcRuleItem(ruleId) {
      this.$api.socialSecurity
        .GetSsafRuleDetail({ ruleId, operateType: 2 })
        .then(res => {
          const data = this.$refs.editTable.formatTableData(res.data.data, 2);
          this.$set(this.editForm, 'ssRuleItemList', JSON.parse(JSON.stringify(data.ssRuleItemList)));
          this.$set(this.editForm, 'afRuleItemList', JSON.parse(JSON.stringify(data.afRuleItemList)));
          // this.editForm.ssRuleItemList = data.ssRuleItemList;
          // this.editForm.afRuleItemList = data.afRuleItemList;
          this.$forceUpdate();
        });
    },


    handleCityChange(data) {
      this.editForm.ssafCity = data.insuredCity;
      this.editForm.ssafCityId = data.insuredCityId;
      this.editForm.isuredRecordModel.ssafCity = data.insuredCity;
      this.editForm.isuredRecordModel.ssafCityId = data.insuredCityId;
    },

    /**
     * @description 监听日期选择器修改
     */
    handleDateChange(date, type) {
      this.editForm[type + 'Year'] = date.substring(0, 4) * 1;
      this.editForm[type + 'Month'] = date.substring(5, 7) * 1;
      this.editForm.isuredRecordModel[type + 'Year'] = date.substring(0, 4) * 1;
      this.editForm.isuredRecordModel[type + 'Month'] = date.substring(5, 7) * 1;
    },

    /**
     * @description 打开当前参保记录详情弹窗
     */
    handleGoInsuredDetails(rowData) {
      this.activeData = rowData;
      this.isShowDetail = true;
    },

    /**
     * @description 监听规则下拉框修改
     */
    handleRuleChange(ruleId) {
      // console.log('参保规则变化');
      const ruleData = this.ruleList.find(e => e.ruleId == ruleId);
      const propList = [
        { name: 'ssafId', base: null, selectName: 'ruleId' },
        { name: 'ssafName', base: "", selectName: 'ruleName' },
        { name: 'ssafCityId', base: 0, selectName: 'insuredCityId' },
        { name: 'ssafCity', base: "", selectName: 'insuredCity' }
      ];

      // 为editForm以及editForm.isuredRecordModel中需要修改数据进行修改
      if (ruleId) { //选择了规则
        propList.map(prop => {
          this.editForm[prop.name] = ruleData[prop.selectName];
          this.editForm.isuredRecordModel[prop.name] = ruleData[prop.selectName];
        });
        this.searhcRuleItem(ruleId);
      } else { //清空选择
        propList.map(prop => {
          this.editForm[prop.name] = prop.base;
          this.editForm.isuredRecordModel[prop.name] = prop.base;
        });
        this.editForm.ssRuleItemList = JSON.parse(JSON.stringify(this.initialTableData.ssRuleItemList));
        this.editForm.afRuleItemList = JSON.parse(JSON.stringify(this.initialTableData.afRuleItemList));
      }

      this.$forceUpdate();
    },

    /**
     * @description 增员，编辑点击确认提交
     */
    handleSubmit() {
      const subId = this.infoData.subId;
      // 从editTable中获取表格数据
      let data = JSON.parse(JSON.stringify(this.editForm));
      !data.ssafId ? data.ssafId = 0 : '';
      !data.isuredRecordModel.ssafId ? data.isuredRecordModel.ssafId = 0 : '';
      // 如果未选定规则，初始化data以及data.isuredRecordModel中规则字段

      // 如果是增员，在社保公积金每项数据中添加subId
      if (this.pageStatus == 2) {
        data.subId = subId;
        data.isuredRecordModel.subId = subId;
        if (data.ssafId == 0) { //如果未选定规则 为社保公积金列表中每项值添加subId
          data.ssRuleItemList = data.ssRuleItemList.map(e => {
            e.subId = subId;
            return e;
          });
          data.afRuleItemList = data.afRuleItemList.map(e => {
            e.subId = subId;
            return e;
          });
        }
      }

      // 是调整
      if (this.pageStatus == 3) {
        data['effectYear'] = parseInt(this.effectDate ? this.effectDate.slice(0, 4) : 0);
        data['effectMonth'] = parseInt(this.effectDate ? this.effectDate.slice(-2) : 0);
      }
      if (data.ssafId > 0) {
        data.ssRuleItemList = [];
        data.afRuleItemList = [];
      }
      // 为添加userId
      data.userId = this.infoData.userId;
      data.isuredRecordModel.userId = this.infoData.userId;
      // 对数据进行格式化 字符串转小数

      data = this.$refs.editTable.formatTableData(data, 1);
      if (this.pageStatus == 4) {
        data['initMonth'] = data.initYear + '-' + `0${data.initMonth}`.slice(-1);
        data['selfPayBeginMonth'] = this.supplementaryPayDate[0];
        data['selfPayEndMonth'] = this.supplementaryPayDate[1];
      }
      // console.log(data, this.effectDate);
      this.$emit('submit', data, this.pageStatus == 2 ? true : false);
    },
    handleGoBack() {
      console.log('famhui');
      this.$emit('goBack', true);
    }

  },
};
</script>
<style lang="less" scoped>
@import url("../less/editCard.less");

#InsuredIndex {
  .staffInfo {
    text-align: center;

    p {
      font-weight: 700;
      font-size: 24px;
      text-align: center;
      margin-bottom: 10px;
    }

    span {
      display: inline-block;
      font-size: 14px;
      color: #666666;
      margin: 10px 20px;
    }
  }

  .record {
    .searchDate {
      margin-bottom: 20px;
    }
  }

  .footer {
    text-align: center;
  }
  .monthrange {
    width: 250px;
    // border: ;
    border-top: none;
    border-left: none;
    border-right: none;
    border-radius: 0;
  }
}
</style>